package wordsCloud;

import com.kennycason.kumo.CollisionMode;
import com.kennycason.kumo.WordCloud;
import com.kennycason.kumo.WordFrequency;
import com.kennycason.kumo.bg.PixelBoundryBackground;
import com.kennycason.kumo.font.scale.LinearFontScalar;
import com.kennycason.kumo.nlp.FrequencyAnalyzer;
import com.kennycason.kumo.palette.ColorPalette;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class WordCloudDistr {
    public static final String PATH = "ruoyi-hzhtest/src/main/resources/";

    public List<WordFrequency> wordsSegment(String str) {

        return null;
    }

    public void createSimpleImage() throws IOException {

        final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        frequencyAnalyzer.setWordFrequenciesToReturn(300);
        frequencyAnalyzer.setMinWordLength(4);
//        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());
//        frequencyAnalyzer.setStopWords(loadStopWords());

        // 从文件中读取词频数据
        List<WordFrequency> wordFrequencies = readWordFrequencyFromFile(PATH + "Files/Paragraph");
        System.out.println(wordFrequencies);

        final Dimension dimension = new Dimension(300, 187);
        final WordCloud wordCloud = new WordCloud(dimension, CollisionMode.PIXEL_PERFECT);
        wordCloud.setPadding(2);
        wordCloud.setBackground(new PixelBoundryBackground(PATH + "Images/whale_small.png"));
        wordCloud.setColorPalette(new ColorPalette(new Color(0x4055F1), new Color(0x408DF1), new Color(0x40AAF1), new Color(0x40C5F1), new Color(0x40D3F1), new Color(0xFFFFFF)));
        wordCloud.setFontScalar(new LinearFontScalar(10, 40));

        // 创建词云
        wordCloud.build(wordFrequencies);
        wordCloud.writeToFile(PATH + "output/whale_wordcloud_small.png");
    }

    private Collection<String> loadStopWords() {
        return null;
    }

    private static List<WordFrequency> readWordFrequencyFromFile(String filename) throws IOException {
        List<WordFrequency> wordFrequencies = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("\\s+");
                if (parts.length == 2) {
                    String word = parts[0];
                    int frequency = Integer.parseInt(parts[1]);
                    wordFrequencies.add(new WordFrequency(word, frequency));
                }
            }
        }
        return wordFrequencies;
    }

}